import { useEffect } from "react";
import { useState } from "react"

// 自定义一个Hooks:
function useStorage(key) {
  const [name, setName] = useState(
    () => {
      const result = JSON.parse(sessionStorage.getItem(key));
      return result
    }
  )
  // 每次通过setName()修改name的值时，就会自动存储 sessionStorage
  // 当name值改变时，就触发useEffect()的执行，做 sessionStorage的存储。
  useEffect(() => {
    sessionStorage.setItem(key, JSON.stringify(name))
  },
    [name]
  )

  return [name, setName]
}



// MyCurrentHooks组件
const MyCurrentHooks = () => {

  const [name, setName] = useStorage('aa');
  useEffect(() => {
    console.log('sessionStorage的aa:', name);
  })

  return (
    <>
      <h1>自定义的hooks:  {name} </h1>
      <button type="button" onClick={() => {
        setName("abc")
      }}>setName</button>
    </>
  )
}

export default MyCurrentHooks